package com.nsharmon.model.transformer;

import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Set;

import com.nsharmon.dao.entity.Axiom;
import com.nsharmon.dao.entity.ContainerAxiom;
import com.nsharmon.dao.entity.EntityObject;

public class ContainerTransformer implements Transformer {
	@Override
	public boolean transformBegin() {
		return true;
	}
	
	@Override
	public Set<Axiom> transform(Set<Axiom> axioms) {
		Set<Axiom> generatedAxioms = new LinkedHashSet<Axiom>();
		
		// Search for extra relationships
		Iterator<Axiom> it = axioms.iterator();
		while(it.hasNext()) {
			Axiom axiom = it.next();
			if(axiom instanceof ContainerAxiom) {
				ContainerAxiom rel = (ContainerAxiom)axiom;
				EntityObject containedEntityObject = rel.getContained();
				
				Set<ContainerAxiom> containerAxioms = getAxiomsByContained(axioms, rel.getContainer());
				for(ContainerAxiom containerLink : containerAxioms) {
					ContainerAxiom ca = new ContainerAxiom();
					ca.setContainer(containerLink.getContainer());
					ca.setContained(containedEntityObject);
					ca.setVariant(containerLink.getVariant());
					
					if(!axioms.contains(ca)) {
						generatedAxioms.add(ca);
					}
				}
			}
		}
		return generatedAxioms;
	}
	
	@Override
	public Set<Axiom> transformEnd( Set<Axiom> axioms ) {
		return null;
	}
	
	private Set<ContainerAxiom> getAxiomsByContained(Set<Axiom> axioms, EntityObject contained) {
		Set<ContainerAxiom> containerAxioms = new LinkedHashSet<ContainerAxiom>();
		for(Axiom axiom : axioms) {
			if(axiom instanceof ContainerAxiom) {
				ContainerAxiom ca = (ContainerAxiom)axiom;
				EntityObject containedEntityObject = ca.getContained();
				if(containedEntityObject.equals(contained)) {
					containerAxioms.add(ca);
				}
			}
		}
		return containerAxioms;
	}
}
